from django.shortcuts import render
from dvadmin.utils.viewset import CustomModelViewSet
from .models import SalesStrategy, SalesPerformance, MarketingPlan
from .serializers import (
    SalesStrategySerializer, SalesStrategyCreateUpdateSerializer,
    SalesPerformanceSerializer, SalesPerformanceCreateUpdateSerializer,
    MarketingPlanSerializer, MarketingPlanCreateUpdateSerializer
)
from rest_framework import viewsets, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.decorators import authentication_classes, permission_classes
from django.db.models import Sum
from decimal import Decimal
from order.models import Order
from datetime import datetime

class SalesStrategyModelViewSet(CustomModelViewSet):
    """
    销售策略管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = SalesStrategy.objects.all()
    serializer_class = SalesStrategySerializer
    create_serializer_class = SalesStrategyCreateUpdateSerializer
    update_serializer_class = SalesStrategyCreateUpdateSerializer

    @action(detail=True, methods=['put'], url_path='update-status')
    def update_status(self, request, pk=None):
        instance = self.get_object()
        status = request.data.get('status')
        if status not in ['pending', 'approved', 'rejected']:
            return Response({'error': '无效的状态值'}, status=400)
        
        instance.status = status
        instance.save()
        
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

class SalesPerformanceModelViewSet(CustomModelViewSet):
    """
    销售业绩管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = SalesPerformance.objects.all()
    serializer_class = SalesPerformanceSerializer
    create_serializer_class = SalesPerformanceCreateUpdateSerializer
    update_serializer_class = SalesPerformanceCreateUpdateSerializer

    @action(detail=False, methods=['get'], permission_classes=[permissions.AllowAny])
    def get_sales_persons(self, request):
        """获取去重后的销售人员列表"""
        # 使用values_list和distinct获取去重后的销售人员名称
        sales_persons = SalesPerformance.objects.values_list('sales_person', flat=True).distinct().order_by('sales_person')
        
        # 过滤掉空值
        valid_persons = [name for name in sales_persons if name]
        
        # 确保列表不为空，添加默认数据
        if not valid_persons:
            valid_persons = ["王小明", "李小红", "张大壮"]
        
        # 构建符合dict-select要求的数据结构
        sales_data = [
            {"value": name, "label": name}
            for name in valid_persons
        ]
        
        # 按照API标准格式返回
        result = {
            "code": 2000,
            "msg": "success",
            "data": sales_data
        }
        
        return Response(result)
        
    @action(detail=False, methods=['get'], permission_classes=[permissions.AllowAny])
    def calculate_actual_amount(self, request):
        """计算销售人员在特定周期内的已完成订单总金额"""
        sales_person = request.query_params.get('sales_person', None)
        period = request.query_params.get('period', None)
        
        if not sales_person or not period:
            return Response({
                "code": 4000,
                "msg": "销售人员和业绩周期参数必须提供",
                "data": 0
            })
        
        try:
            # 将字符串转换为日期对象
            period_date = datetime.strptime(period, '%Y-%m-%d')
            # 获取所选月份的第一天和最后一天
            month_start = period_date.replace(day=1)
            # 计算下个月的第一天
            if period_date.month == 12:
                month_end = datetime(period_date.year + 1, 1, 1)
            else:
                month_end = datetime(period_date.year, period_date.month + 1, 1)
            
            # 计算选定销售人员在选定月份内已完成订单的总金额
            total_amount = Order.objects.filter(
                sales_person=sales_person,
                status=3,  # 已完成订单
                order_date__gte=month_start,
                order_date__lt=month_end
            ).aggregate(total=Sum('total_amount'))['total'] or 0
            
            result = {
                "code": 2000,
                "msg": "success",
                "data": float(total_amount)
            }
            
            return Response(result)
            
        except Exception as e:
            return Response({
                "code": 5000,
                "msg": f"计算订单金额时出错: {str(e)}",
                "data": 0
            })

    @action(detail=True, methods=['put'], url_path='update-actual-amount', permission_classes=[permissions.IsAuthenticated])
    def update_actual_amount(self, request, pk=None):
        """更新销售业绩的实际金额"""
        instance = self.get_object()
        
        try:
            # 获取销售人员和业绩周期信息
            sales_person = instance.sales_person
            period = instance.period
            
            # 获取所选月份的第一天和最后一天
            month_start = period.replace(day=1)
            # 计算下个月的第一天
            if period.month == 12:
                month_end = datetime(period.year + 1, 1, 1).date()
            else:
                month_end = datetime(period.year, period.month + 1, 1).date()
            
            # 计算选定销售人员在选定月份内已完成订单的总金额
            total_amount = Order.objects.filter(
                sales_person=sales_person,
                status=3,  # 已完成订单
                order_date__gte=month_start,
                order_date__lt=month_end
            ).aggregate(total=Sum('total_amount'))['total'] or 0
            
            # 更新实际金额
            instance.actual_amount = total_amount
            
            # 计算并更新达成率
            # 默认设置为0
            instance.achievement_rate = 0
            if instance.target_amount and instance.target_amount > 0:
                instance.achievement_rate = round((total_amount / instance.target_amount) * 100, 2)
            
            # 保存更新后的记录
            instance.save()
            
            # 返回更新后的数据
            serializer = self.get_serializer(instance)
            return Response({
                "code": 2000,
                "msg": "实际金额已成功更新",
                "data": serializer.data
            })
            
        except Exception as e:
            return Response({
                "code": 5000,
                "msg": f"更新实际金额时出错: {str(e)}",
                "data": None
            }, status=500)

class MarketingPlanModelViewSet(CustomModelViewSet):
    """
    市场拓展计划管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = MarketingPlan.objects.all()
    serializer_class = MarketingPlanSerializer
    create_serializer_class = MarketingPlanCreateUpdateSerializer
    update_serializer_class = MarketingPlanCreateUpdateSerializer
